<!-- 房屋管理 -->
<template>
  <div class="root-house-mng">
    <div class="root-house-mng-main">
      <div class="search">
        <div style="margin-bottom: 15px;">
          <a-space direction="vertical" :size="12">
            <a-range-picker v-model:value="value4" :format="dateFormat" />
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space :size="8" v-if="'map' == activeKeyRef">
            <a-button type="primary" @click="handleExport"> 导出 </a-button>
         </space>
        </div>
      </div>
      <BasicTable @register="registerTable">
          <template #id="{ record }"> </template>
      </BasicTable>
    </div>

    <AuditModal @register="registerModal" @success="handleSuccess" />

    <Drawer5 @register="register5">
      <template #drawContent>
        <DataTableList
          v-if="policeVisible"
          :houseId="pickedHouseId"
          ref="housePolicePlaceRef"
          @house-submit="handleSuccess"
        />
        <FireTableList
          v-if="fireVisible"
          :houseId="pickedHouseId"
          ref="houseFirePlaceRef"
          @house-submit="handleSuccess"
        />
        <Tag v-if="!policeVisible && !fireVisible"></Tag>
      </template>
    </Drawer5>
  </div>
</template>

<script lang="ts">
//import maplibregl from '/@/utils/lib/mapre/maplibre-gl.js';
//import '/@/utils/lib/mapre/maplibre-gl.css';
import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getBasicColumns, getSearchFormSchema } from './tableData';
import { PageWrapper } from '/@/components/Page';
import { BasicForm, useForm } from '/@/components/Form/index';
import { Tabs, Space, Divider, Drawer, Tag, Collapse, Button, Popover } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  ComputedRef,
  computed,
  defineAsyncComponent,
  nextTick,
} from 'vue';
import { downloadByUrl } from '/@/utils/file/download';
import { getLouDangerList } from '/@/api/demo/system';
import { useGlobSetting } from '/@/hooks/setting';
const globSetting = useGlobSetting();
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
const { info, success, warning, error } = createMessage;
import { FormProps, FormSchema } from '/@/components/Table';
import AuditModal from './AuditModal.vue';
import { useModal } from '/@/components/Modal';
import type { UserInfo } from '/#/store';
import { SearchOutlined } from '@ant-design/icons-vue';
import Drawer5 from '/@/views/detail/Drawer5.vue';
import { useDrawer } from '/@/components/Drawer';
import dayjs, { Dayjs } from 'dayjs';

const DataTableList = defineAsyncComponent(
  () => import('/@/views/danger/comprehensive/DataTableListMergeAll.vue'),
);

const FireTableList = defineAsyncComponent(
  () => import('/@/views/danger/fire/FireTableListMergeAll.vue'),
);
const dateFormat = 'YYYY-MM-DD';
const startDate = ref<any>(null); // 开始时间
const endDate = ref<any>(null); // 结束时间
const imgList: string[] = [];
export default defineComponent({
  name: 'HouMng',
  components: {
    DataTableList,
    FireTableList,
    ImagePreview,
    BasicTable,
    BasicForm,
    AuditModal,
    TableAction,
    PageWrapper,
    Tabs,
    Divider,
    Drawer5,
    Space,
    SearchOutlined,
    Popover,
    Tag,
    TabPane: Tabs.TabPane,
    Button,
  },
  props: {
    msg: String,
    showMapPopupButtons: {
      type: Boolean,
      default: true,
    },
    policeVisible: {
      type: Boolean,
      default: false,
    },
    fireVisible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { attrs, emit, slots, expose }) {
    const activeKeyRef = ref('map');
    const searchVisible = ref(false);
    const pickedHouse = ref({});
    const pickedHouseId = ref('');
    const houseFirePlaceRef = ref();
    const housePolicePlaceRef = ref();

    const houseMapRef = ref();

    const userStore = useUserStore();

    function getTableActs(record) {
      let acts = [
        {
          icon: 'clarity:map-marker-line',
          tooltip: '定位111',
          onClick: handleLocMap.bind(null, record),
        },
      ];

      if (props.showMapPopupButtons) {
        acts.push({
          icon: 'clarity:tree-view-line',
          tooltip: '核查历史情况',
          onClick: handlePlaceView.bind(null, record),
        });
      }

      return acts;
    }

    let protocol = window.document.location.protocol;
    let host = window.document.location.host;
    let localhostPath = protocol + '//' + host;

    const mapopC: maplibregl.Popup[] = [];
    function clickPopUpOk(_) {
      if (mapopC.length > 0) {
        mapopC[0].remove();
      }
    }

    const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();

    //获取当前房屋的历史纪录(自查\检查\核查)
    function clickPopupButtonOk(obj) {
      console.log(obj);
        setDrawerProps({
        destroyOnClose: true,
        showDetailBack: false,
        afterVisibleChange: (visible: boolean) => {
          if (visible) {
            nextTick(() => {
              // houseFirePlaceRef.value.onHouseSelected(obj.id);
              // housePolicePlaceRef.value.onHouseSelected(obj.id);
            });
          }
        },
      });
        openDrawer5(true);
    }

    const [registerModal, callbackUseModal] = useModal();
    const [registerTable, { reload, getForm }] = useTable({
        api: getLouDangerList,
      columns: getBasicColumns(),
      pagination: { pageSize: 50 },
      formConfig: {
          schemas: [],
      },
        useSearchForm: false,
      bordered: false,
    });

    const value4 = ref<[Dayjs, Dayjs]>([
      dayjs('2015/01/01', dateFormat),
      dayjs('2015/01/01', dateFormat),
    ]);

    function handleReloadCurrent() {
      reload(); //刷新当前页
    }
    function toMapData(data, prefix, ret) {
      for (let d in data) {
        if (typeof data[d] == 'object') {
          toMapData(data[d], d, ret);
        } else {
          if (prefix) {
            ret[`${prefix}.${d}`] = data[d];
          } else {
            ret[d] = data[d];
          }
        }
      }
    }

    function encodeData(data) {
      let dv = {};
      toMapData(data, '', dv);
      return Object.keys(dv)
        .map(function (key) {
          return [key, dv[key]].map(encodeURIComponent).join('=');
        })
        .join('&');
    }

    function handleExport() {
      const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
      const tk = userStore.getToken;

      const fv = getForm().getFieldsValue();
      const searchParams = encodeData(fv);
      console.log(searchParams);
      downloadByUrl({
        url: `${uriBase}/houses/datas/export?access_token=${tk}&${searchParams}`,
        target: '_blank',
      });
    }

    function handleReload() {
      reload({
        page: 1,
      });
    }

    function handleSuccess() {
      reload();
    }

    function handlePreview(record: Recordable) {
      const onImgLoad = ({ index, url, dom }) => {
        console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
      };
      imgList.length = 0;
      if (record.photos) {
        let photos = record.photos.split(',');
        photos.forEach((ele) => {
          if (ele) imgList.push(`${globSetting.apiBaseUrl}/api/v1/images22222/${ele}`);
        });
      }
      // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
      createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
    }

    function handleStatus(a: Recordable) {
      var record = JSON.parse(JSON.stringify(a));
      callbackUseModal.openModal(true, {
        record,
        isUpdate: true,
      });
    }

    function onPopupButtonOkClick(obj) {
      clickPopupButtonOk(obj);
    }

    function handlePlaceView(record: Recordable) {
      clickPopupButtonOk(record);
    }

    function handleLocMap(record: Recordable) {
      activeKeyRef.value = 'map';
      houseMapRef.value.handleLocMap(record);
    }

    function locMap(houseId) {
      houseMapRef.value.locMap(houseId);
    }

    const getFormProps = computed((): Partial<FormProps> => {
      return {
        showAdvancedButton: false,
        compact: true,
        actionColOptions: { span: 6 },
        schemas: cloneSearchSchema(serSchema),
      };
    });

    function handleSearchInfoChange(info: Recordable) {}
    const [registerForm, formActions] = useForm();
    const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
      const keys = Object.keys(slots);
      return keys
        .map((item) => (item.startsWith('form-') ? item : null))
        .filter((item) => !!item) as string[];
    });
    function replaceFormSlotKey(key: string) {
      if (!key) return '';
      return key?.replace?.(/form\-/, '') ?? '';
    }
    const showDrawer = () => {
      searchVisible.value = true;
    };
    return {
      imgList,
      activeKeyRef,
      registerForm,
      getFormSlotKeys,
      replaceFormSlotKey,
      getFormProps,
      handleSearchInfoChange,
      registerTable,
      handlePreview,
      handleLocMap,
      handleStatus,
      handleReloadCurrent,
      handleExport,
      handleReload,
      locMap,
      registerModal,
      handleSuccess,
      searchVisible,
      showDrawer,
      register5,
      pickedHouse,
      pickedHouseId,
      houseFirePlaceRef,
      housePolicePlaceRef,
      houseMapRef,
      getTableActs,
      onPopupButtonOkClick,
      handlePlaceView,
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  //z-index: 100;
  //position: absolute;
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;
  //background-color: rgba(34, 34, 34, 0.6);
  :deep(.ant-form) {
    margin-top: 6px;
  }

  // :deep(.ant-form-item-label) > label {
  //   color: white;
  // }
}
</style>
